//  爱营销工单详情原生版本
//  NewMissonListDetailController.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2018/3/27.
//  Copyright © 2018年 zjhcsoftios. All rights reserved.
//

#import "NewMissonListDetailController.h"
#import "NewMissonListDetailCell.h"
#import "NewMissonListDetailButtomView.h"
#import "HCGFReceiptView.h"
#import "ZPwaihuShowView.h"
#import "ZPchaxunModel.h"
#import "ZPwaihuaListViewController.h"
#import "NewMissionBusinessNumberProcessView.h"
#import "ZPHCNewReassignPeopleListViewController.h"
#import <MessageUI/MessageUI.h>
#import "ZPAddBlacklistView.h"
#import "ZSBStatusInfo.h"
#import "NewOrderDetailViewController.h"
#import "NewMissonListDeatilHeadView.h"
#import "NewMarketWebViewController.h"
#import "MissionWebMask.h"
#import "NewMissonListController.h"
#import "NewOrdorListViewController.h"
#import "NirKxMenu.h"
#import "NSBundle+AssociatedBundle.h"
#import "UIColor+EX.h"
#import "NetworkAddress.h"
#import "SVProgressHUD.h"
#import "iSeeNetworkRequest.h"

@interface NewMissonListDetailController ()<UITableViewDelegate,UITableViewDataSource,NewMissionListDetailButtomViewDelegate,MFMessageComposeViewControllerDelegate,ZPwaihuShowViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *buttomBackView;//底部背景
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttomViewHeight;//底部页面高度
@property (weak, nonatomic) IBOutlet UITableView *tableView;//展示列表

@property (nonatomic, strong) NSArray *moreButtomList;//更多列表

@property (nonatomic, strong) NSMutableArray *dataList;//数据列表

@property (nonatomic, strong) NewMissonListDetailButtomView *buttomView;//底部栏

@property (nonatomic,copy) NSString *kehuhuaxiang;

@property (nonatomic, strong) NSMutableArray *phoneList;//联系人号码
@property (nonatomic, copy)NSDictionary *yewuhaoma;
@property (nonatomic, copy) NSString * businessCode; //业务号码

@property (nonatomic, strong) ZPwaihuShowView *waihuView;

@property (nonatomic, strong) NewMissonListDeatilHeadView *head;

//退回任务单输入文字
@property (nonatomic, strong) NSString *backNote;
@property (nonatomic, strong) UIAlertAction *backAction;

@end

@implementation NewMissonListDetailController

static NSString *newMissonListDetailCellIdentify = @"newMissonListDetailCellIdentify";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_tableView registerNib:[UINib nibWithNibName:@"NewMissonListDetailCell" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] forCellReuseIdentifier:newMissonListDetailCellIdentify];
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.backgroundColor = [UIColor colorWithHexString:@"EAECEF"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _head = [[NewMissonListDeatilHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
    _head.backgroundColor = [UIColor colorWithHexString:@"EAECEF"];
    _head.ordorId = self.ordorId;
    _tableView.tableHeaderView = _head;
    
    self.title = @"任务单详情";
    
    [self getNewDetail];
    

    //初始化退回
    _backAction = [UIAlertAction actionWithTitle:@"退回" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        [params setObject:self.model.orderId forKey:@"orderIds"];
        if (self.backNote.length) {
            [params setObject:self.backNote forKey:@"message"];
        }
        //   退回接口
        [SVProgressHUD showWithStatus:@"退回中"];
        
        [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl ,ZPHCOrderListtuihui) params:params success:^(id object) {
            if ([object[@"code"] integerValue] == 200) {
                
                [SVProgressHUD showSuccessWithStatus:@"退回成功"];
                //成功后 返回上一界面
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADNEWMISSONLIST" object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"退回失败"];
        }];
        
    }];
    _backAction.enabled = NO;
}

#pragma mark 网络请求

- (void)getNewDetail {
    
    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    [parma setObject:_ordorId forKey:@"orderId"];
    
    if (!_isOrdorListEnter) {
        if (_logId.length) {
            [parma setObject:_logId forKey:@"logId"];
        }
    }
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl, ZPNewMissionListDetail) params:parma success:^(id object) {
        if ([object[@"code"] integerValue] == 200) {
            
            self.model = [NewMissionListDetailModel mj_objectWithKeyValues:object[@"body"]];
            self.logId = self.model.logId;
            self.buttomView.isOrdorListEnter = self.isOrdorListEnter;
            self.buttomView.detailModel = self.model;
            self.buttomView.logId = self.model.logId;
            self.head.ordorId = self.ordorId;

            [self.tableView reloadData];
            [SVProgressHUD dismiss];
        }
    } failure:^(NSError *error) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [dic objectForKey:@"msg"];
        [SVProgressHUD showErrorWithStatus:msg];
    }];
    
    _backAction.enabled = NO;
}




#pragma mark tableView 

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataList.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewMissonListDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:newMissonListDetailCellIdentify forIndexPath:indexPath];
    cell.titleLabel.text = [NSString stringWithFormat:@"%@:", _dataList[indexPath.row][@"k"]];
    cell.detailLabel.text = _dataList[indexPath.row][@"v"];
    
    if ([_dataList[indexPath.row][@"k"] isEqualToString:@"客户名"]) {
        [cell showManuscripts];
        [cell.manuscripts addTarget:self action:@selector(manuscriptsButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }else {
        [cell hiddenManuscripts];
    }
    
    if ([_dataList[indexPath.row][@"k"] isEqualToString:@"业务号码"] || [_dataList[indexPath.row][@"k"] isEqualToString:@"联系人号码"] || [_dataList[indexPath.row][@"k"] isEqualToString:@"催单次数"]) {
        cell.detailLabel.textColor = [UIColor colorWithHexString:@"169BD5"];
    }else {
        cell.detailLabel.textColor = [UIColor colorWithHexString:@"444444"];
    }
    
    if ([_dataList[indexPath.row][@"k"] isEqualToString:@"备注信息"]) {
        NSString *remind = _dataList[indexPath.row][@"v"];
        if (remind.length > 0) {
            cell.detailLabel.textColor = [UIColor colorWithHexString:@"169BD5"];
        }else {
            cell.detailLabel.textColor = [UIColor colorWithHexString:@"999999"];
            cell.detailLabel.text = @"点击输入备注";
        }
    }
    
    if ([_dataList[indexPath.row][@"k"] isEqualToString:@"联系人号码"] || [_dataList[indexPath.row][@"k"] isEqualToString:@"备注信息"]) {
        
        cell.inputImage.hidden = NO;
        cell.detailLabelLeft.constant = 15 + 26;
    }else {
        cell.inputImage.hidden = YES;
        cell.detailLabelLeft.constant = 15;
    }
    
    
    if (_dataList.count - 1 == indexPath.row) {
        cell.buttomLine.hidden = YES;
    }else {
        cell.buttomLine.hidden = NO;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   

    NSDictionary *dicInfo = _dataList[indexPath.row];
    if ([dicInfo[@"p"] integerValue] == 1) {
        NSString *phone = dicInfo[@"v"];
        
        _phoneList = [self addPhoneNumArr:phone];
        
        UIAlertView *    customAlertView = [[UIAlertView alloc] initWithTitle:@"修改联系号码" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [customAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
        customAlertView.tag = 10000;
        UITextField *nameField = [customAlertView textFieldAtIndex:0];
        nameField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        nameField.placeholder = @"联系号码为空时无法修改";
        nameField.keyboardType = UIKeyboardTypeNumberPad;
        [customAlertView show];
    }
    
    if ([dicInfo[@"b"] integerValue] == 1) {
        UIAlertView *    customAlertView = [[UIAlertView alloc] initWithTitle:@"修改备注" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [customAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
        customAlertView.tag = 1000 +indexPath.row;
        UITextField *nameField = [customAlertView textFieldAtIndex:0];
        nameField.placeholder = @"请输入备注";
        
        [customAlertView show];
    }
    
    
    
    
    //任务单流转信息 点击业务号码 显示
    
    if ([dicInfo[@"k"] isEqualToString:@"业务号码"]) {
        
        [NewMissionBusinessNumberProcessView showBusinessNumberProcessView:self.view orderId:_model.orderId BusinessNumber:dicInfo[@"v"]];
        
    }else if ([dicInfo[@"k"] isEqualToString:@"催单次数"]) {
        HCGFReceiptView *webView = [[HCGFReceiptView alloc] init];
        NSString *url =[NMarketMainUrl stringByAppendingString:_model.viewHurryOrderUrl];
        webView.title =@"催单次数";
        webView.url =url;
        [self.navigationController pushViewController:webView animated:YES];
    }
}


#pragma mark 数据处理

- (void)setModel:(NewMissionListDetailModel *)model {
    _model = model;
    
    if (_model.content.length > 0) {
        NSMutableArray *arraya = [model.content mj_JSONObject];
        
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (NSDictionary *dic in arraya) {
            if ([dic isKindOfClass:[NSDictionary class]]) {
                if ([dic[@"h"] integerValue] != 1 ) {
                    [array addObject:dic];
                }
                
                NSString * kName = [dic objectForKey:@"k"];
                if ([kName isEqualToString:@"业务号码"]){
                    self.businessCode = [dic objectForKey:@"v"];
                    
                }
            }
        }
        self.dataList = array;
    }
}

#pragma mark 底部代理

- (void)NewMissionListDetailButtomViewButtonAction:(AppModuleModel *)selectedModel MoreList:(NSArray *)moreList {
    if (moreList) {
        
        self.moreButtomList = moreList;
        [self showMoreBottomMenu];
        
    }else {
        [self buttomButtonAction:selectedModel];
    }
}

- (void)showMoreBottomMenu {
    
    
    CGFloat buttonWidth = (kScreenWidth - 75) / 4;
    
    NSMutableArray *kxItems = [NSMutableArray array];
    for (AppModuleModel *model in self.moreButtomList) {
        KxMenuItem * menuItem = [KxMenuItem menuItem:model.name
                                               image:nil
                                              target:self
                                              action:@selector(kxMenuAction:)];
        menuItem.foreColor = [UIColor colorWithHexString:model.styleColor];
        menuItem.alignment = NSTextAlignmentCenter;
        [kxItems addObject:menuItem];
    }
    
    
    OptionalConfiguration  abcd =   {
        .arrowSize = 9,  //指示箭头大小
        .marginXSpacing = 15,  //MenuItem左右边距
        .marginYSpacing = 9,  //MenuItem上下边距
        .intervalSpacing = 30,  //MenuItemImage与MenuItemTitle的间距
        .menuCornerRadius = 5,  //菜单圆角半径
        .maskToBackground = true,  //是否添加覆盖在原View上的半透明遮罩
        .shadowOfMenu =false,  //是否添加菜单阴影
        .hasSeperatorLine = true,  //是否设置分割线
        .seperatorLineHasInsets =YES,  //是否在分割线两侧留下Insets
        .menuBackgroundColor = {.R = 1, .G = 1, .B = 1},  //menuItem字体颜色
        
    };
    
    [KxMenu showMenuInView:self.view fromRect:CGRectMake((buttonWidth + 15) * 3 , kScreenHeight - 51 - Height_NavBar - kSafeAreaInsetsBottom, buttonWidth + 30, 51) menuItems:kxItems withOptions:abcd];
}


#pragma mark 业务处理

//销讲稿页面跳转
-(void)manuscriptsButtonAction{
    HCGFReceiptView *webView = [[HCGFReceiptView alloc] init];
    NSString *url =[NMarketMainUrl stringByAppendingString:_model.viewXjgUrl];
    webView.title =@"销讲稿";
    webView.url =url;
    [self.navigationController pushViewController:webView animated:YES];
    
}



- (void )kxMenuAction:(KxMenuItem *) item {
    
    
    for (AppModuleModel *model in self.moreButtomList) {
        if ([item.title isEqualToString:model.name]) {
            
            [self buttomButtonAction:model];
        }
    }

}




- (void)buttomButtonAction:(AppModuleModel *) model {
    
   
    if ([model.logId isEqualToString:@"0"]) {
        
        [UIView animateWithDuration:0.25 animations:^{

        }];
        
    }else {
        if ([model.logId isEqualToString:@"5048"]) {
            //转派
            ZPHCNewReassignPeopleListViewController * viewCtrl = [[ZPHCNewReassignPeopleListViewController alloc] init];
            viewCtrl.billIds = self.model.orderId;
            viewCtrl.zpHdImageFlag = self.model.zpHdImageFlag;
            viewCtrl.zpRemarkFlag = self.model.zpRemarkFlag;
            [self.navigationController pushViewController:viewCtrl animated:YES];

        }else if ([model.logId isEqualToString:@"5045"]) {
            //受理
            if (model.enterType == 2) {
                HCGFReceiptView *receiptView = [[HCGFReceiptView alloc] init];
                receiptView.url = model.enterUrl;
                
                [self.navigationController pushViewController:receiptView animated:YES];
            }
        }else if ([model.logId isEqualToString:@"5047"]) {
            //回单

            __weak NewMissonListDetailController *wself = self;
            [MissionWebMask showReceiptView:self.view.window isReceipt:YES detailIds:self.model.orderId phoneNum:self.businessCode url:nil success:^(NSString *successStr) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"回单成功" message:@"请选择转跳页面" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"工单首页" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [wself.navigationController popToRootViewControllerAnimated:YES];
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"工单列表" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSArray * array = wself.navigationController.viewControllers;
                    for (NSInteger i = array.count-1; i >= 0; i--) {
                        UIViewController *ctrl = self.navigationController.viewControllers[i];
                        if ([ctrl isKindOfClass:[NewMissonListController class]] || [ctrl isKindOfClass:[NSClassFromString(@"NewOrdorListViewController") class]]) {
                            [wself.navigationController popToViewController:ctrl animated:YES];
                        }
                    }
                }]];
                
                [self presentViewController:alert animated:YES completion:nil];

            } failure:^{
                
            }];
            //回单埋点
//            [[MovementRecord shareRecord] addRecordWithCode:ZPCodehuidan andContent:self.model.orderId];
            
        }
        else if ([model.logId isEqualToString:@"5050"]) {
            
            
            //商机
            HCGFReceiptView *receiptView = [[HCGFReceiptView alloc] init];
            receiptView.url = model.enterUrl;
            [self.navigationController pushViewController:receiptView animated:YES];
            //商机埋点
//            [[MovementRecord shareRecord] addRecordWithCode:ZPCodeshangji andContent:self.model.detailId];
        
        }else if ([model.logId isEqualToString:@"5051"]) {
            //支付

        }else if ([model.logId isEqualToString:@"5055"]) {
            //电话
            
            NSMutableDictionary *dic = [model.attachment mj_JSONObject];
            
            if (dic==nil ) {
                return;
            }
            NSMutableArray *arr =[dic objectForKey:@"ywhm"];
            if (arr.count) {
                _yewuhaoma = [arr objectAtIndex:0];
            }
            _phoneList = [dic objectForKey:@"lxrhm"];
        
            
            
            if (!self.waihuView) {
                
                self.waihuView = [[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"] loadNibNamed:@"ZPwaihuShowView" owner:nil options:nil].lastObject;
                self.waihuView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            }
            self.waihuView.ordorId = self.model.orderId;
            self.waihuView.delegate = self;
            self.waihuView.yewuhaoma = self.yewuhaoma;
            self.waihuView.phoneList = self.phoneList;

            [self.waihuView showWithView:self.view.window];
            
//            [[MovementRecord shareRecord] addRecordWithCode:ZPCodedianhua andContent:self.model.detailId];
            
        }else if ([model.logId isEqualToString:@"5052"]) {
            //受理状态
            ZSBStatusInfo *statusInfo = [[ZSBStatusInfo alloc] init];
            statusInfo.type = 1;
            statusInfo.tradeOrderNum = _model.tradeOrderNum;
            NewOrderDetailViewController *viewCtrl = [[UIStoryboard storyboardWithName:@"ZPaiyingxiao" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] instantiateViewControllerWithIdentifier:@"NewOrderDetailViewController"];;
            viewCtrl.statusInfo =statusInfo;

            [self.navigationController pushViewController:viewCtrl animated:YES];

        }else if ([model.logId isEqualToString:@"5053"]) {

            //商机状态
            ZSBStatusInfo *statusInfo = [[ZSBStatusInfo alloc] init];
            statusInfo.type = 1;
            statusInfo.tradeOrderNum = _model.tradeOrderNum;
            NewOrderDetailViewController *viewCtrl = [[UIStoryboard storyboardWithName:@"ZPaiyingxiao" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] instantiateViewControllerWithIdentifier:@"NewOrderDetailViewController"];;
            viewCtrl.statusInfo =statusInfo;
            [self.navigationController pushViewController:viewCtrl animated:YES];
            
        }else if ([model.logId isEqualToString:@"5056"]) {
            [self jiedanduidiaoqingqiu:self.model.orderId];
        }else if([model.logId isEqualToString:@"5057"]){

            //任务单流程
            HCGFReceiptView *receiptView = [[HCGFReceiptView alloc] init];
            receiptView.url = model.enterUrl;
            receiptView.title = @"任务单流程";
            [self.navigationController pushViewController:receiptView animated:YES];
            
        }else if ([model.logId isEqualToString:@"5059"]){
            //抢单
            if ([self.logId isEqualToString:@"548"]) {
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                [params setObject:self.model.projectId forKey:@"projectId"];
                [params setObject:self.logId forKey:@"logId"];
                [params setObject:self.model.orderId forKey:@"orderIds"];
                [SVProgressHUD showWithStatus:@"抢单中"];
                
                [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl,ZPHCOrderListqiangdanchiqiangdan) params:params success:^(id object) {
                    if ([object[@"code"] integerValue] == 200) {
                        [SVProgressHUD showSuccessWithStatus:@"抢单成功"];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"ROBORDERSUCCESSED" object:nil];
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                    [SVProgressHUD showErrorWithStatus:@"抢单失败"];
                } failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"抢单失败"];
                }];
                
                
            }else {
                [SVProgressHUD showWithStatus:@"抢单中" ];
                NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                [params setObject:self.model.orderId forKey:@"orderIds"];
                //    抢单回调
                
                [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPHCOrderListqiangdanhuidiao) params:params success:^(id object) {
                    [SVProgressHUD showSuccessWithStatus:@"抢单成功"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ROBORDERSUCCESSED" object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                } failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"抢单失败"];
                }];
                
            }
        }else if ([model.logId isEqualToString:@"5060"]) {
            //撤单
            NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
            //                if (self.myRewardInfo.detailId){
            [params setObject:self.model.orderId forKey:@"orderIds"];
            //                }
            if (_logId != 0) {
                [params setObject:self.logId forKey:@"logId"];
            }
            
            [SVProgressHUD showWithStatus:@"撤单中"];
            
            [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl,ZPHCZhuanpaichedan) params:params success:^(id object) {
                [SVProgressHUD showSuccessWithStatus:@"撤单成功"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADNEWMISSONLIST" object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                });
            } failure:^(NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"撤单失败"];
            }];
            
           
        }else if ([model.logId isEqualToString:@"5061"]) {
            //实时查询
            HCGFReceiptView *webView = [[HCGFReceiptView alloc] init];
            webView.title =@"实时查询";
            webView.url =model.enterUrl;
            webView.urla = model.enterUrl;
            
            [self.navigationController pushViewController:webView animated:YES];
            
        }else if ([model.logId isEqualToString:@"5062"]) {
            //客户画像
            
            HCGFReceiptView *webView = [[HCGFReceiptView alloc] init];
            webView.title =@"客户画像";
            
            _kehuhuaxiang = model.enterUrl;
            webView.url = [NSString stringWithFormat:@"%@num=%@", model.enterUrl, self.businessCode];
            webView.urla = [NSString stringWithFormat:@"%@num=%@", model.enterUrl, self.businessCode];
            
            [self.navigationController pushViewController:webView animated:YES];
            
            
        }else if ([model.logId isEqualToString:@"5063"]) {
            //套餐推荐
            
            HCGFReceiptView *webView = [[HCGFReceiptView alloc] init];
            webView.title = model.name;
            webView.url =model.enterUrl;
            
            [self.navigationController pushViewController:webView animated:YES];
            
        }else if([model.logId isEqualToString:@"5064"]){
            //发票
            HCGFReceiptView *webView = [[HCGFReceiptView alloc] init];
            webView.title =model.name;
            webView.url =model.enterUrl;
            
            [self.navigationController pushViewController:webView animated:YES];
            
        }else if ([model.logId isEqualToString:@"5066"]){
            //补换卡
            HCGFReceiptView *webView = [[HCGFReceiptView alloc] init];
            webView.title =model.name;
            webView.url =model.enterUrl;
            
            [self.navigationController pushViewController:webView animated:YES];
            
        }else if ([model.logId isEqualToString:@"5067"]){
            //退回
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退单原因" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                textField.placeholder = @"请输入退单备注";
                
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChange:) name:UITextFieldTextDidChangeNotification object:textField];

            }];
            
            [alert addAction:_backAction];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            
            [self presentViewController:alert animated:YES completion:nil];
            
        }else if ([model.logId isEqualToString:@"5065"]){
        //批量重新处理
            NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
            [params setObject:self.model.orderId forKey:@"orderIds"];
            
            //重新处理
            [SVProgressHUD showWithStatus:@"重新处理中"];
            
            
            [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPHCOrderListchongxinchuli) params:params success:^(id object) {
                [SVProgressHUD showSuccessWithStatus:@"重新处理成功"];
            } failure:^(NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"重新处理失败"];
            }];
            
            
            
        }else if ([model.logId isEqualToString:@"5069"]) {
            //派单
            ZPHCNewReassignPeopleListViewController * viewCtrl = [[ZPHCNewReassignPeopleListViewController alloc] initWithIsPZ:YES];
            viewCtrl.billIds = self.model.orderId;
            viewCtrl.zpHdImageFlag = self.model.zpHdImageFlag;
            [self.navigationController pushViewController:viewCtrl animated:YES];
        }else if ([model.logId isEqualToString:@"5070"]) {
            //客户视图
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择资产类型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            // 0.移动 1.固话 2.宽度
            [alert addAction:[UIAlertAction actionWithTitle:@"移动" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self pushCustomerWebView:[model.enterUrl stringByReplacingOccurrencesOfString:@"numberType=" withString:@"numberType=0"] Title:model.name];
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"固话" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self pushCustomerWebView:[model.enterUrl stringByReplacingOccurrencesOfString:@"numberType=" withString:@"numberType=1"] Title:model.name];
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"宽带" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self pushCustomerWebView:[model.enterUrl stringByReplacingOccurrencesOfString:@"numberType=" withString:@"numberType=2"] Title:model.name];
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            
            [self presentViewController:alert animated:YES completion:nil];
        }else if ([model.logId isEqualToString:@"5071"]) {
            
            
            [MissionWebMask showBusinessNumberProcessView:self.view.window isReceipt:YES url:model.enterUrl success:^(NSString *success) {
                [SVProgressHUD showSuccessWithStatus:@"预约成功"];
                [self getNewDetail];
            } failure:^{
                
            }];
        
            
        }
        
        
    }
    
}


- (NSMutableArray *)addPhoneNumArr:(NSString *)text
{
    //匹配电话号码
    NSArray *array_phonenum = [text mj_JSONObject];
    NSMutableArray *phoneNumArr = [NSMutableArray arrayWithArray:array_phonenum];
    for (NSString * string in array_phonenum) {
        if ([self checkTelNumber:string]) {
            [phoneNumArr addObject:string];
        }
    }
    
    return phoneNumArr;
}

- (BOOL)checkTelNumber:(NSString *) telNumber
{
    //匹配电话号码
    NSString *pattern = @"\\d{3}-\\d{7}|\\d{3}-\\d{7}|\\d{4}-\\d{8}|\\d{4}-\\d{8}|1+[35789]+\\d{9}|\\d{8}|\\d{7}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}

#pragma mark 网络请求

//修改备注
- (void)changebeizhu:(NSMutableDictionary *)dic content:(NSString *)str{
    {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        if (_model.orderId) {
            [params setObject:_model.orderId forKey:@"detailId"];
        }
        [params setObject:dic[@"c"] forKey:@"columnName"];
        if (str.length) {
            [params setObject:str forKey:@"columnNameValue"];
        }
        [SVProgressHUD showWithStatus:@"处理中"];
        
        [iSeeNetworkRequest postWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl,ZPHCchangebeizhu) params:params success:^(id object) {
            [dic setObject:str forKey:@"v"];
            [self.tableView reloadData];
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"修改失败"];
        }];
    }
}

//修改电话号码
- (void)changephonenumber:(NSString *)number Remove:(NSString *) remove{
    {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        [params setObject:_model.orderId forKey:@"orderId"];
        if (number) {
            [params setObject:number forKey:@"telNumber"];
        }
        if (remove) {
            [params setObject:remove forKey:@"changeFlag"];
        }
        [SVProgressHUD showWithStatus:@"处理中"];
        
        [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl,ZPHCchangephonenumber) params:params success:^(id object) {
            
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            
            [self getNewDetail];
        } failure:^(NSError *error) {
            
            [SVProgressHUD showErrorWithStatus:@"修改失败"];
            
        }];
        
    }
}

//记录完信息之后调用拨打电话接口
-(void)phone:(NSString *)str{
    
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    if (_model.orderId) {
        [params setObject:_model.orderId forKey:@"documentId"];
    }
    [params setObject:str forKey:@"calledNum"];
    
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl, ZPcallphone) params:params success:^(id object) {
        
        NSString *phonaa =[@"118312052"  stringByAppendingString:str];
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phonaa];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:telUrl]];
        });
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"外呼记录失败"];
    }];
    
}

- (void)senderMessage:(NSString *)str {
    if([MFMessageComposeViewController canSendText]) {
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        if (_model.orderId) {
            [params setObject:_model.orderId forKey:@"orderId"];
        }
        
        [params setObject:@"111" forKey:@"ywhm"];
        
        [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@", NMarketMainUrl,ZPHmessagenbody) params:params success:^(id object) {
            if ([MFMessageComposeViewController canSendText]) {
                MFMessageComposeViewController *vc =[[MFMessageComposeViewController alloc] init];
                vc.body = object[@"body"][@"result"];
                vc.recipients = [NSArray arrayWithObjects:str,nil];
                vc.navigationBar.tintColor = [UIColor colorWithRed:0.1877 green:0.5138 blue:0.9837 alpha:1.0];
                [vc setMessageComposeDelegate:self];
                [self  presentViewController:vc animated:YES completion:nil];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"获取短信内容失败"];
        }];
        
    }else {
        [SVProgressHUD showErrorWithStatus:@"无法发送短信"];
    }
    
}


- (void)searchWaihuList:(NSString *) phone {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:phone forKey:@"callednumber"];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPchaxun) params:params success:^(id object) {
        NSArray *list = [ZPchaxunModel mj_objectArrayWithKeyValuesArray:object[@"body"][@"result"]];
        NSLog(@"%@",list);
        [self.waihuView removeFromSuperview];
        ZPwaihuaListViewController *vc = [[ZPwaihuaListViewController alloc] init];
        vc.list = list;
        [self.navigationController pushViewController:vc animated:YES];
    } failure:^(NSError *error) {
        
    }];
    
}

//批量接单
-(void)jiedanduidiaoqingqiu:(NSString *)allid{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:allid forKey:@"orderIds"];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPHCWorkorderListkjiedan) params:params success:^(id object) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"操作成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"去处理" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.logId = @"521";
            [SVProgressHUD show];
            [self getNewDetail];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"返回上级" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADNEWMISSONLIST" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"接单失败"];
    }];
    
}

#pragma mark 发送iMessage代理
//短信控制器处理
-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    
    switch (result) {
        case MessageComposeResultSent:
            //信息传送成功
            
            break;
        case MessageComposeResultFailed:
            //信息传送失败
            
            break;
        case MessageComposeResultCancelled:
            //信息被用户取消传送
            
            break;
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - actionsheet delegate
//修改电话号码
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 10000) {
        if (buttonIndex == alertView.firstOtherButtonIndex) {
            UITextField *nameField = [alertView textFieldAtIndex:0];
            //如果是数字才请求修改代码
            if ([self isPureInt:nameField.text]) {
                [self changephonenumber:nameField.text Remove:@"update"];
            }
        }
    }else{
        if (buttonIndex == alertView.firstOtherButtonIndex) {
            
            NSMutableDictionary *dic = _dataList[alertView.tag - 1000];
            UITextField *nameField = [alertView textFieldAtIndex:0];
            [self changebeizhu:dic content:nameField.text];
        }
    }
    
    
}




#pragma mark 查询列表

- (void)pushCustomerWebView:(NSString *) enterUrl Title:(NSString *) title {
    
    NewMarketWebViewController *web = [[NewMarketWebViewController alloc] init];
    web.loadUrl = enterUrl;
    web.title = title;
    [self.navigationController pushViewController:web animated:YES];
}


//支付
/*
 
 - (void)oneKeyPay:(UIButton *)button
 {
 if (!self.businessCode || self.businessCode.length == 0)
 {
 [self presentFailureTips:@"没有业务号码，不支持一键支付"];
 return;
 }
 
 
 UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"请选择你要缴费的资产类型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
 [sheet addAction:[UIAlertAction actionWithTitle:@"移动" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 [self loadOnkeyPayInfo:@"TEL"];
 [[MovementRecord shareRecord] addRecordWithCode:HCCodeMyOrderOneKeyPay andContent:self.model.detailId];
 }]];
 [sheet addAction:[UIAlertAction actionWithTitle:@"固话" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 [self loadOnkeyPayInfo:@"GH"];
 [[MovementRecord shareRecord] addRecordWithCode:HCCodeMyOrderOneKeyPay andContent:self.model.detailId];
 }]];
 [sheet addAction:[UIAlertAction actionWithTitle:@"宽带" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 [self loadOnkeyPayInfo:@"KD"];
 [[MovementRecord shareRecord] addRecordWithCode:HCCodeMyOrderOneKeyPay andContent:self.model.detailId];
 }]];
 
 [sheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
 
 }]];
 
 }

 
 - (void) loadOnkeyPayInfo:(NSString *) action{
 
 SuccessBlock success = ^ (id object)
 {
 NSLog(@"%@",[object description]);
 if ([object[@"code"] integerValue] == 200)
 {
 if (object[@"body"] && [object[@"body"] isKindOfClass:[NSDictionary class]])
 {
 NSDictionary *body = object[@"body"];
 if (body)
 {
 NSString * chargeUrl = [body objectForKey:@"chargeUrl"];
 if (!chargeUrl || chargeUrl.length > 0)
 {
 //                        跳转到浏览器
 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:chargeUrl]];
 }
 }
 }
 }
 };
 FailBlock fail = ^ (id object)
 {
 NSLog(@"%@",[object description]);
 };
 
 NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
 [params setValue:self.businessCode forKey:@"zchm"];
 [params setValue:action forKey:@"zclx"];
 [[HCNewNetManager sharedManager] getOnkeyPayUrl:params success:success fail:fail];
 }
 */

#pragma mark 外呼弹出页面代理
- (void)iconImageSelect:(NSString *)phone ImageTag:(NSInteger)tag Remove:(NSString *)remove HeiFlag:(BOOL)heiFlag{
    switch (tag) {
        case 0:
            if (!heiFlag) {
                [self phone:phone];
            }else {
                [SVProgressHUD showErrorWithStatus:@"黑名单号码，禁止外呼"];
            }
            break;
        case 1:
            if (!heiFlag) {
                [self senderMessage:phone];
            }else {
                [SVProgressHUD showErrorWithStatus:@"黑名单号码，禁止发送短信"];
            }
            break;
        case 2:
            [self searchWaihuList:phone];
            break;
        case 3:
        {
            if (!heiFlag) {
                [ZPAddBlacklistView showBlacklistViewPhoneNum:phone];
            }else {
                [SVProgressHUD showErrorWithStatus:@"已是黑名单号码，请勿重复提交！"];
            }
        }
            break;
        case 4:
        {
            [self changephonenumber:phone Remove:remove];
        }
        default:
            break;
    }
}


- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

//字典转字符串
-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

#pragma mark 懒加载

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (NSArray *)moreButtomList {
    if (!_moreButtomList) {
        _moreButtomList = [[NSArray alloc] init];
    }
    return _moreButtomList;
}

- (NSMutableArray *)phoneList {
    if (!_phoneList) {
        _phoneList = [NSMutableArray array];
    }
    return _phoneList;
}

- (NewMissonListDetailButtomView *)buttomView {
    if (!_buttomView) {
        _buttomView = [[NewMissonListDetailButtomView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 51)];
        [self.buttomBackView addSubview:_buttomView];
        self.buttomView.delegate = self;
    }
    return _buttomView;
}


//监听退回输入框中文字输入
-(void)textFieldTextChange:(NSNotification *)noti{
    UITextField *currentTextField = (UITextField *)noti.object;
    if (currentTextField.text.length > 0) {
        _backNote = currentTextField.text;
        _backAction.enabled = YES;
    }else {
        _backAction.enabled = NO;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
